package com.itcast.flink.window.session;

import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * Flink Window 窗口计算：基于时间会话窗口SessionWindow，会话超时时间间隔5s
 * todo 某条数据来了以后，后续超过5s钟没有数据达到，将前面数据当做一个窗口，进行数据计算
 *
 * @author lilulu
 */
public class TimeSessionWindowDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> inputStream = env.socketTextStream("node1", 9999);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<String> windowStream = inputStream.filter(line -> line.trim().length() > 0).map(new MapFunction<String, Integer>() {
            @Override
            public Integer map(String s) throws Exception {
                System.out.println("item:" + s);
                return Integer.parseInt(s);
            }
        }).windowAll(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
                .apply(new AllWindowFunction<Integer, String, TimeWindow>() {
                    private FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

                    @Override
                    public void apply(TimeWindow timeWindow, Iterable<Integer> iterable, Collector<String> collector) throws Exception {
                        String windowStart = format.format(timeWindow.getStart());
                        String windowEnd = format.format(timeWindow.getEnd());
                        int sum = 0;
                        for (Integer temp : iterable) {
                            sum += temp;
                        }
                        String output = "window: [" + windowStart + " ~ " + windowEnd + "], sum = " + sum ;
                        collector.collect("sum=" + sum);
                    }
                });
        // 4. 数据终端-sink
        windowStream.printToErr();
        // 5. 触发执行-execute
        env.execute("TimeSessionWindowDemo");
    }
}